package cn.edu.neu.lab603.cloudeval.entity.model.power

import cn.edu.neu.lab603.cloudeval.entity.PhysicalMachine

import scala.io.Source

/** 根据 PowerSpec 2008 测试数据的能耗模型。
  *
  * Created by yfwz100 on 2016/11/10.
  */
class SpecPowerModel(val name: String) extends PowerModel {

  // 获取能耗数据
  private val powerData = Source.fromInputStream(getClass.getResourceAsStream(name)).getLines().map(_.toDouble.toInt).toSeq

  override def getPower(host: PhysicalMachine): Long = {
    val utilization = host.getUsedResPct("mips")
    assert(!(utilization < 0 || utilization > 1), "Utilization value must be between 0 and 1")
    if (utilization % 0.1 == 0) {
      getPowerData((utilization * 10).toInt)
    } else {
      val utilization1: Int = Math.floor(utilization * 10).toInt
      val utilization2: Int = Math.ceil(utilization * 10).toInt
      val power1: Double = getPowerData(utilization1)
      val power2: Double = getPowerData(utilization2)
      val delta: Double = (power2 - power1) / 10
      (power1 + delta * (utilization - utilization1.toDouble / 10) * 100).toLong
    }
  }

  protected def getPowerData(index: Int): Int = powerData(index)
}
